import React from 'react';
import {connect} from 'dva';
import { Toast } from 'antd-mobile';
import ReactDOM from 'react-dom';
import styles from './indexPage.less';
import Constants from '@/utils/constants';
import {
  deviceReady,
  exitWebView,
  setLeftBtn,
  uploadFile
} from '@/utils/cordova';
import {
  NavBar,
  Icon,
  SegmentedControl,
  PullToRefresh,
  Button,
  Accordion,
  List
} from 'antd-mobile';

const NUM_ROWS = 20;
let pageIndex = 0;

class IndexPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      segmentedsValues: [
        {
          'cacheName': 'Todo',
          'apiEffects': 'getTodoList',
        }, {
          'cacheName': 'Processed',
          'apiEffects': 'getProcessedList',
        }, {
          'cacheName': 'Applications',
          'apiEffects': 'getApplicationList',
        }, {
          'cacheName': 'Drafts',
          'apiEffects': 'getDraftList',
        }
      ],
      segmenteds: [
        'Todo', 'Processed', 'Applications', 'Drafts'
      ],
      segmentedIndex: 0,
      listLables: [
        'CaseNo', 'Company', 'Created', 'Status'
      ],
      down: true,
      refreshing: true,
      height: document.documentElement.clientHeight
    }
  }

  setNativeLeftBtn = () => {
    window.cordovaEvents.exitWebView = exitWebView;
    window.cordovaBackEvents = exitWebView;
    setLeftBtn('cordovaEvents.exitWebView()');
  }

  componentDidMount() {
    this.removeModal();
    // document.ontouchmove = function(e){
    //   e.preventDefault();
    // }
    if(Constants.hasCordova){
      deviceReady().then(this.handleRecoverStatus)
    }else{
      this.handleRecoverStatus();
    }
  }

  removeModal = () => {
    //倒序删除，才能删的干净
    for(let i = document.getElementsByClassName('am-modal-mask').length - 1; i >= 0; i-- ){
      const wrap =  document.getElementsByClassName('am-modal-mask')[i];
      wrap.parentElement.parentElement.remove();
    }
  }

  handleRecoverStatus = () => {
    const footerHei = 44;
    const hei = this.state.height - ReactDOM.findDOMNode(this.refs.list).offsetTop - footerHei;
    this.setState({
      segmentedIndex: this.props.indexPageSegmentedIndex,
      height: hei
    });
    ReactDOM.findDOMNode(this.refs.list).scrollTop = this.props.indexPageScrollTop;
    this.handleCurrentListRefresh(this.props.indexPageSegmentedIndex);
  }

  handleSegmentedChange = (e) => {
    this.setState({segmentedIndex: e.nativeEvent.selectedSegmentIndex});
    this.handleCurrentListRefresh(e.nativeEvent.selectedSegmentIndex);
  }

  handleCurrentListRefresh = (index) => {
    // 0 => false
    const currentSegmented = this.state.segmentedsValues[index] || this.state.segmentedsValues[this.state.segmentedIndex];
    console.log(currentSegmented);
    this.props.dispatch({type: `user/getList`, payload:{api: currentSegmented.apiEffects, cacheName: currentSegmented.cacheName}});
  }

  handleGoDetail = (item) => {
    this.props.dispatch({type: `keepStatus/save`, payload:{
      indexPageSegmentedIndex: this.state.segmentedIndex,
      indexPageScrollTop: ReactDOM.findDOMNode(this.refs.list).scrollTop
    }});
    const actionType = this.handleGetDetailActionType(item, this.state.segmenteds[this.state.segmentedIndex]);
    // this.props.history.push(`/detail?id=${item.id}&actionType=${actionType}`);
    this.props.history.push({pathname: '/detail', search: `id=${item.id}&actionType=${actionType}`})
  }

  handleGetDetailActionType = (item, from) => {
    let actionType = '';
    switch (from) {
      case 'Todo':
      if(item._type == 'toDoMap'){
        if(item.status == 'Accounting Approvel'){
          actionType = 'viewUpdateRequestInWorkFlow';
        }else{
          actionType = 'viewWorkflowEntry';
        }
      }else{
        if(item.status == 'Accounting Process'){
          actionType = 'viewUpdateAdvanceInWorkFlow';
        }else{
          actionType = 'viewWorkflowEntryAdv';
        }
      }
      break;
      case 'Processed' :
        if(item._type == 'processedList'){
          actionType = 'viewWorkflowEntry';
        }else{
          actionType = 'viewWorkflowEntryAdv';
        }
      break;
      case 'Applications' :
        actionType = 'viewWorkflowEntry';
      break;
      case 'Drafts' :
        actionType = 'viewUpdateForm';
      break;
      default:
    }
    return actionType;
  }

  handleGoNewApplication = ()=>{
    this.props.history.push(`/new`);
  }

  render() {
    return (
      <div className={styles.normal}>
        {
          !Constants.hasCordova
          ?
          <NavBar
            mode='dark'
            icon={< Icon type = 'left' />}
            onLeftClick={() => console.log('onLeftClick')}
            rightContent={[< Icon key = '1' type = 'ellipsis' />]}>
            Travel Request System
          </NavBar>
          :
          null
        }
        <SegmentedControl className={styles.segmented} selectedIndex={this.state.segmentedIndex} values={this.state.segmenteds} onChange={this.handleSegmentedChange}/>
        <div className={styles.listLables}>
        {
            this.state.listLables.map((item) => {
            return <span key={item}>{item}</span>
          })
        }
        </div>
        <PullToRefresh damping={60} ref='list' style={{
          height: this.state.height,
          overflow: 'auto'
        }} indicator={this.state.down
          ? {}
          : {
            deactivate: '上拉可以刷新'
          }} direction={this.state.down
          ? 'down'
          : 'up'} refreshing={this.props.refreshing} onRefresh={this.handleCurrentListRefresh}>
          {this.props.list.map((item, index) => (
            <div key={item.id} className={styles.item} onClick={() => this.handleGoDetail(item)}>
              <div>{item.caseNo || item.advanceNo || 'New'}</div>
              <div>{item.companyCode} {item.companyName}</div>
              <div>{global.moment(item.created).format('YYYY-MM-DD HH:mm')}</div>
              <div>{item.status}</div>
            </div>
          ))}
        </PullToRefresh>
        <div className={styles.footerBtn} onClick={this.handleGoNewApplication}>
          New Application
        </div>
      </div>
    )
  };
}

IndexPage.propTypes = {};

function mapStateToProps(state) {
  return {
    ...state.user,
    ...state.keepStatus
  }
}
export default connect(mapStateToProps)(IndexPage);
